package com.example.testdemo.home;

import android.app.Activity;
import android.app.ActivityManager;
import android.content.Context;

import java.util.Stack;

/**
 * 作    者：MrYan （QQ：416643088）
 * 创建日期：6/27 0027.
 * 活跃Activity集合
 */

public class ActivityManagers {
    /**
     * Activity集合
     */
    private static ActivityManagers mActivityManagers;
    private static Stack<Activity> activityStack;
    /**
     * 私有构造器
     */
    private ActivityManagers() {
        activityStack = new Stack<>();
    }
    /**
     * 获取实例
     *
     * @return 实例
     */
    public static synchronized ActivityManagers getInstance() {
        if (mActivityManagers == null) {
            mActivityManagers = new ActivityManagers();
        }
        return mActivityManagers;
    }

    public boolean isEmpty(){
        return activityStack.isEmpty();
    }

    /**
     * 添加Activity
     *
     * @param activity 活动
     */
    public void addActivity(Activity activity) {
        activityStack.add(activity);
    }


    /**
     * 获取当前Activity（堆栈中最后一个压入的）
     */
    public Activity getCurrentActivity() {
        if (isEmpty()) return null;
        return activityStack.lastElement();
    }

    /**
     * 获取上一个Activity
     */
    public Activity getPreviousActivity(){
        if (activityStack.size() > 1){
            return activityStack.get(activityStack.size() - 2);
        }
        return activityStack.peek();
    }

    /**
     * 结束当前Activity（堆栈中最后一个压入的）
     */
    public void finishActivity() {
        Activity activity = activityStack.lastElement();
        if (activity != null) {
            activity.finish();
        }
    }

    /**
     * 结束指定的Activity
     */
    public void finishActivity(Activity activity) {
        if (activity != null) {
            activityStack.remove(activity);
            activity.finish();
        }
    }

    /**
     * 结束指定类名的Activity
     */
    public void finishActivity(Class<?> cls) {
        for (Activity activity : activityStack) {
            if (activity.getClass().equals(cls)) {
                finishActivity(activity);
            }
        }
    }

    /**
     * 关闭所有Activity
     */
    public void finishAllActivity() {
        for (int i = 0; i < activityStack.size(); i++) {
            activityStack.get(i).finish();
        }
        activityStack.clear();
    }

    /**
     * 退出应用程序
     */
    public void AppExit(Context context) {
        try {
            finishAllActivity();
            ActivityManager activityMgr = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
            if (activityMgr == null) return;
            activityMgr.restartPackage(context.getPackageName());
            System.exit(0);
        } catch (Exception ignore) {
        }
    }
}
